package upload;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/17 17:14
 */

//传输文件的客户端
public class TCPFileUploadClient {

    public static void main(String[] args) throws IOException {

        //客户端连接服务端的8888端口，得到Socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);

        //创建读取文件磁盘的输入流
        String file = "E:\\java基础\\面试之路\\interview-road\\计算机基础\\计算机网络\\images\\三次握手.png";
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

        //bytes就是file对应的字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        bis.close();

        //通过socket获取到输出流，将bytes数据发送给服务器
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        bos.write(bytes);
        //设置写入数据结束的结束标记
        socket.shutdownOutput();

        //4.通过输入流，接收服务端发过来的消息
        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf)) != -1){
            System.out.println(new String(buf,0,readLen));
        }

        //关闭资源
        inputStream.close();
        bos.close();
        socket.close();

    }
}
